package bb.lanxing.mvp.presetner;

import static bb.lanxing.manager.SharedManager.KEY_TOKEN;
import static bb.lanxing.manager.SharedManager.LOGIN_STYLE_OTHER;
import static bb.lanxing.manager.SharedManager.LOGIN_STYLE_QQ;
import static bb.lanxing.manager.SharedManager.LOGIN_STYLE_WECHAT;
import static bb.lanxing.manager.SharedManager.LOGIN_STYLE_WEIBO;

import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.socialize.bean.SHARE_MEDIA;

import androidx.annotation.NonNull;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.interfaces.ILoginModel;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.User;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.util.JsonUtil;
import bb.lanxing.util.text.TextUtils;
import okhttp3.Call;
import rx.Observable;
import rx.schedulers.Schedulers;

public class LoginModelImpl implements ILoginModel {
    @NonNull
    @Override
    public Observable<User> login(@NonNull final String phone, @NonNull String pwd) {
        return Observable.create(new NetSubscribe(MyHttpClient.accountNumLogin(phone, pwd)))
                .subscribeOn(Schedulers.io()).flatMap(result -> {
                    try {
                        Observable<User> ret = setUserInfo(result);
                        SharedManager.getInstance().setLoginStyle(LOGIN_STYLE_OTHER);
                        return ret;
                    } catch (JSONException e) {
                        App.getContext().showMessage(R.string.mine_login_toast_login_failed);
                        return null;
                    }
                });
    }

    @NonNull
    @Override
    public Observable<User> loginByThirdParty(@NonNull final SHARE_MEDIA share_media, @NonNull JSONObject jSONObject) {
        return Observable.create(new NetSubscribe(MyHttpClient.userSigninByThirdParty(jSONObject)))
                .subscribeOn(Schedulers.io()).flatMap(result -> {
                    try {
                        Observable<User> ret = setUserInfo(result);
                        if (share_media == SHARE_MEDIA.QQ) {
                            SharedManager.getInstance().setLoginStyle(LOGIN_STYLE_QQ);
                        } else if (share_media == SHARE_MEDIA.WEIXIN) {
                            SharedManager.getInstance().setLoginStyle(LOGIN_STYLE_WECHAT);
                        } else if (share_media == SHARE_MEDIA.SINA) {
                            SharedManager.getInstance().setLoginStyle(LOGIN_STYLE_WEIBO);
                        } else {
                            SharedManager.getInstance().setLoginStyle(LOGIN_STYLE_OTHER);
                        }
                        return ret;
                    } catch (Exception e) {
                        App.getContext().showMessage(R.string.mine_login_toast_login_failed);
                        return null;
                    }
                });
    }

    @NonNull
    @Override
    public Observable<User> loginSms(@NonNull String phone, @NonNull String code) {
        Call accountNumLogin = MyHttpClient.accountSmsLogin(phone, code);
        return Observable.create(new NetSubscribe(accountNumLogin)).subscribeOn(Schedulers.io()).flatMap(result -> {
            try {
                Observable<User> ret = setUserInfo(result);
                SharedManager.getInstance().setLoginStyle(LOGIN_STYLE_OTHER);
                return ret;
            } catch (JSONException e) {
                App.getContext().showMessage(R.string.mine_login_toast_login_failed);
                return null;
            }
        });
    }

    private Observable<User> setUserInfo(String str) throws JSONException {
        JSONObject jSONObject = new JSONObject(str);
        String token = JsonUtil.getStringValue(KEY_TOKEN, jSONObject);
        SharedManager.getInstance().setValue(KEY_TOKEN, token);

        JSONObject jSONObjectData = jSONObject.getJSONObject("data");
        int userid = jSONObjectData.optInt("userid");
        long birthday = jSONObjectData.optLong("birthday");
        double weight = jSONObjectData.optDouble("weight");
        int height = jSONObjectData.optInt("height");
        int gender = jSONObjectData.optInt("gender");
        String province = jSONObjectData.optString("province");
        String city = jSONObjectData.optString("city");
        String nickName = jSONObjectData.optString("nickName");
        String phone = jSONObjectData.optString("phone");
        int level = jSONObjectData.optInt("level");
        int score = jSONObjectData.optInt("score");

        User userByUid = User.getUserByUid(userid);
        if (userByUid == null) {
            userByUid = new User();
            userByUid.setUid(userid);
        }
        if (TextUtils.isEmptyOrNull(nickName)) {
            nickName = "";
        }
        userByUid.setNickName(nickName);
        userByUid.setLevel(level);
        userByUid.setScore(score);

        if (TextUtils.isEmptyOrNull(nickName)) {
            nickName = "";
        }
        userByUid.setNickName(nickName);

        String avatar = jSONObjectData.optString("avatar");
        if (TextUtils.isEmptyOrNull(avatar)) {
            avatar = "";
        }
        userByUid.setPhotoUrl(avatar);
        String username = jSONObjectData.getString("username");
        String enuid = jSONObjectData.getString("enuid");

        userByUid.setBirthday(birthday);
        userByUid.setWeight(weight);
        userByUid.setHeight(height);
        userByUid.setProvince(province);
        userByUid.setCity(city);
        userByUid.setGender(gender);
        userByUid.setName(username);
        userByUid.setEnuid(enuid);
        if (TextUtils.isEmptyOrNull(phone)) {
            phone = "";
        }
        userByUid.setPhone(phone);
        SharedManager.getInstance().setUserPhone(phone);
        return Observable.just(userByUid);
    }
}
